﻿using StarryEdge.Core.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StarryEdge.Devices.Protocol.Modbus
{
    public class TCP_Modbus_Protocol : IProtocol
    {
        private byte _slave;
        public TCP_Modbus_Protocol(byte slave)
        {
            _slave = slave;
        }

        public byte[] Deserialize(IList<byte> data)
        {
            switch (data[7])
            {
                case 0x03:
                    return data.Skip(9).Take(data[8]).ToArray();
                case 0x06:

                    break;
                case 0x10:

                    break;
            }
            return data.ToArray();
        }

        public byte[] Serialize(IList<byte> data)
        {
            List<byte> result = new List<byte>() { 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, _slave };
            result.AddRange(data);
            switch (data[0])
            {
                case 0x03:
                case 0x06:
                    result[5] = 6;
                    break;
                case 0x10:
                    short value = (short)(data.Count + 1);
                    result[4] = (byte)(value >> 8);
                    result[5] = (byte)(value);
                    break;
            }
            return result.ToArray();
        }

        public bool Verify(IList<byte> bytes)
        {
            if (bytes == null || bytes.Count < 6) { return false; }
            int length = bytes[4] << 8 | bytes[5];
            if (bytes.Count < length)
            {
                return false;
            }
            if (bytes[7] > 16)
            {
                throw new Exception($"Modbus tcp 错误代码：{bytes[7]}");
            }
            return true;
        }
    }
}
